﻿#include "OptmvLampControl.h"
#include <QDebug>

OptmvLampControl::OptmvLampControl()
    : m_type(NONE),
      m_handle(0)
{
}

OptmvLampControl::~OptmvLampControl()
{
    close();
}


bool OptmvLampControl::valueRange(int channel, int &min, int &max)
{
    Q_UNUSED(channel);
    min = 0;
    max = 255;
    return true;
}

bool OptmvLampControl::close()
{
    switch (m_type)
    {
    case ETHERNET:
        OPTController_DestroyEthernetConnection(m_handle);
        //OPTController_DestoryEtheConnection(m_handle);
        break;
    case SERIALPORT:
        OPTController_ReleaseSerialPort(m_handle);
    default:
        break;
    }
    m_handle = 0;
    return true;
}

bool OptmvLampControl::connectBySerialPort(QString port)
{
    if(m_handle)
    {
        close();
    }
    long ret = OPTController_InitSerialPort(port.toLatin1().data(), &m_handle);
    m_type = SERIALPORT;
    return ret == OPT_SUCCEED;
}

bool OptmvLampControl::connectByIP(QString ip)
{
    if(m_handle)
    {
        close();
    }
    long ret = OPTController_CreateEthernetConnectionByIP(ip.toLatin1().data(), &m_handle);
    m_type = ETHERNET;
    return ret == OPT_SUCCEED;
}

bool OptmvLampControl::connectByName(QString name)
{
    if(m_handle)
    {
        close();
    }
    long ret = OPTController_CreateEthernetConnectionBySN(name.toLatin1().data(), &m_handle);
    m_type = ETHERNET;
    return ret == OPT_SUCCEED;
}


bool OptmvLampControl::setEnable(int channel, bool on)
{
    if(m_handle == 0)
        return false;
    long ret = OPT_ERR_TURNOFFCH_FAILED;
    if(on)
    {
        ret = OPTController_TurnOnChannel(m_handle, channel);
    }
    else
    {
        ret = OPTController_TurnOffChannel(m_handle, channel);
    }
    return OPT_SUCCEED == ret;
}

bool OptmvLampControl::setValue(int channel, int intensity)
{
    if(m_handle == 0)
        return false;
    intensity = qBound(0, intensity, 255);
    long lRet = OPTController_SetIntensity(m_handle, channel, intensity);
    if (OPT_SUCCEED == lRet)
    {
        return true;
    }
    return false;
}

int OptmvLampControl::value(int channel)
{
    if(m_handle == 0) return 0;
    int intensity;
    long lRet = OPTController_ReadIntensity (m_handle, channel, &intensity);
    if (OPT_SUCCEED == lRet)
    {

        return intensity;
    }
    return 0;
}
